package fox.framework.rpc.endpoint;


import fox.framework.rpc.context.aware.RpcEventPublisherAware;
import fox.framework.rpc.context.event.RpcEventPublisher;
import fox.framework.rpc.exception.RpcException;
import fox.framework.rpc.server.dispatcher.RpcRequestDispatcher;

import java.util.concurrent.ThreadFactory;

/**
 * Rpc终端发送抽象类
 * @author cuichao
 * @Description: AbstractRpcEndPoint
 * @Date: create in 2020/12/29 16:30
 */
public abstract class AbstractRpcEndPoint implements RpcEndPoint , Runnable , RpcEventPublisherAware {

    protected int port;

    protected String address;

    protected RpcRequestDispatcher dispatcher;

    protected volatile Throwable cause;

    private Thread thread;

    protected boolean enableServer = true;

    protected RpcEventPublisher publisher;

    @Override
    public void setRpcEventPublisher(RpcEventPublisher publisher) {
        this.publisher = publisher;
    }

    @Override
    public void publish() throws RpcException {
        thread = new ServerThreadFactory().newThread(this);
        thread.start();
        beforeStarted();
        if(cause != null){
            throw new RpcException(cause);
        }
        System.err.println("启动成功");
    }

    @Override
    public void setRequestDispatcher(RpcRequestDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    private final class ServerThreadFactory implements ThreadFactory{

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r,"rpc-server-thread");
        }

    }


    protected void beforeStarted(){
        //nothing to do
    }



    protected RpcRequestDispatcher getDispatcher(){
        return this.dispatcher;
    }

    protected RpcEventPublisher getPublisher(){
        return publisher;
    }



}
